package cn.anecansaitin.industrialization_expansion.common.util;

import com.google.common.io.Files;
import com.google.gson.JsonObject;
import net.minecraft.util.JSONUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;

public class JsonFileReader {
    private static final Logger LOGGER = LogManager.getLogger();

    @Nullable
    public static JsonObject read(File file) {
        if (!file.isFile() && !file.getName().endsWith(".json")) {
            LOGGER.error("Try to read json from path, but the file is not a json: {}", file);
            return null;
        }

        BufferedReader reader = null;

        try {
            reader = Files.newReader(file, StandardCharsets.UTF_8);
            return JSONUtils.parse(reader);
        } catch (FileNotFoundException e) {
            LOGGER.error("Can't find the json file: {}", file);
        } finally {
            IOUtils.closeQuietly(reader);
        }

        return null;
    }
}
